package cn.yy.init;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.StandardServletEnvironment;

import java.net.*;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * springboot项目启动后，进行自定义的初始化操作
 */
@Component
public class ApplicationInit implements CommandLineRunner {

    @Value("${server.port}")
    private int port;
    @Autowired
    private Environment env;
    //正则匹配规则
    private static final String REG;
    //正则表达式对象
    private static final Pattern PATTERN;

    static {
        REG = "\\[(.*)\\]";
        PATTERN = Pattern.compile(REG);
    }

    // 启动后自动调用该方法
    @Override
    public void run(String... args) throws Exception {
        showInfo();
    }


    private void showInfo(){
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String host = address.getHostAddress();
        System.out.println("*******************swagger访问地址********************");
        System.out.println("http://"+host+":"+port+"/swagger-ui.html");
        System.out.println("http://*********:"+port+"/swagger-ui.html");
        System.out.println("*******************swagger访问地址********************");

        System.out.println();

        System.out.println("*****************本次启动激活的profile*****************");
        System.out.println("当前激活的profile: "+ Arrays.toString(env.getActiveProfiles()));
        System.out.println("*****************本次启动激活的profile*****************");

        System.out.println();

        System.out.println("*****************本次启动读取的配置文件*****************");
        StandardServletEnvironment sse = (StandardServletEnvironment) env;
        sse.getPropertySources().forEach(ps->{
            if(ps instanceof OriginTrackedMapPropertySource){
                OriginTrackedMapPropertySource ot = (OriginTrackedMapPropertySource) ps;
                System.out.println(findConfigFile(ot.getName()));
            }
        });
        System.out.println("*****************本次启动读取的配置文件*****************");
    }

    /**
     * 使用正则表达式，查找配置文件，例如 [application.yml]
     * @param line
     * @return
     */
    private static String findConfigFile(String line) {

        Matcher m = PATTERN.matcher(line);

        if(m.find()){
            return m.group();
        }

        return null;

    }
}
